<template>
    <div></div>
</template>

<script>
import { checkBind } from '@/api/login'
import {
    setToken,
    getOAuth2AccessToken,
    getOAuth2RefreshToken,
    setOAuth2AccessToken,
    removeOAuth2RefreshToken,
    removeOAuth2AccessToken
} from '@/utils/auth'
import { refreshToken } from '@/api/oauth2/oauth2'

export default {
    inject: ['reload'],
    name: 'CheckBind',
    data() {
        return {
            form: {},
            rules: {}
        }
    },
    watch: {
        $route: {
            handler: function(route) {
                this.redirect = route.query && route.query.redirect
            },
            immediate: true
        }
    },
    created() {
        this.init()
    },
    methods: {
        init() {
            if (getOAuth2AccessToken()) {
                checkBind().then(response => {
                    let data = response.data
                    if (data !== undefined) {
                        let cause = data.cause
                        console.log('checkBind cause', cause)
                        if (cause !== undefined) {
                            // console.log('cause', cause)
                            // this.refreshToken()
                            return
                        } else {
                            let token = data.token
                            setToken(token)
                        }
                    }
                    this.$router.push({ path: this.redirect || '/' }).catch(() => {
                    })
                }, error => {
                    console.log('checkBind error', error)
                    if (error.message === '902') {
                        this.refreshToken()
                    }
                })
            } else {
                this.$router.push({ path: this.redirect || '/oauth2/login' }).catch(() => {
                })
            }
        },
        refreshToken() {
            refreshToken({ refreshToken: getOAuth2RefreshToken() }).then(response => {
                console.log('刷新token', response)
                setOAuth2AccessToken(response.data.access_token)
                this.reload()
            }, error => {
                console.log('刷新token出错', error)
                removeOAuth2RefreshToken()
                removeOAuth2AccessToken()
            })
        }
    }
}
</script>

<style rel="stylesheet/scss" lang="scss">
</style>
